package xyz.ibenben.zhongdian.system.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;
import xyz.ibenben.zhongdian.common.annotation.SystemControllerLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.common.exception.ExceptionEnum;
import xyz.ibenben.zhongdian.common.exception.MyException;
import xyz.ibenben.zhongdian.common.util.HttpServletResponseUtil;
import xyz.ibenben.zhongdian.system.entity.ChinaCity;
import xyz.ibenben.zhongdian.system.entity.ChinaRegion;
import xyz.ibenben.zhongdian.system.entity.HouseInfo;
import xyz.ibenben.zhongdian.system.entity.HouseLocation;
import xyz.ibenben.zhongdian.system.entity.ajax.AjaxJson;
import xyz.ibenben.zhongdian.system.entity.enums.HouseTypeEnum;
import xyz.ibenben.zhongdian.system.entity.sys.SysUser;
import xyz.ibenben.zhongdian.system.form.HouseInfoForm;
import xyz.ibenben.zhongdian.system.service.HouseInfoService;
import xyz.ibenben.zhongdian.system.service.HouseLocationService;
import xyz.ibenben.zhongdian.system.service.elasticsearch.ElasticsearchHouseInfoService;
import xyz.ibenben.zhongdian.system.service.impl.RedisService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 房屋信息控制类
 * 提供了一些基本的服务，如初始化、获取房屋信息列表等方法。
 * spring mvc思想 通过controller来调用service里的方法，
 * service里的方法再通过调用Dao来实现对数据的操作
 * 返回值统统是String类型的返回页面有统一的安排方便代码提取
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Slf4j
@Controller
@SessionAttributes("houseInfoForm")
@RequestMapping("/houseInfo")
@SuppressWarnings(value = "unchecked")
public class HouseInfoController extends BaseController {
    /**
     * 实体名称
     */
    private static final String ENTITYNAME = "houseInfo";

    @Resource
    private HouseInfoService houseInfoService;
    @Resource
    private ElasticsearchHouseInfoService elasticsearchHouseInfoService;
    @Resource
    private RedisService redisService;
    @Resource
    private HouseLocationService houseLocationService;

    @InitBinder
    public void binder(WebDataBinder binder) {
        //转换日期
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        // CustomDateEditor为自定义日期编辑器
        binder.registerCustomEditor(Date.class, "buyTime", new CustomDateEditor(dateFormat, true));

    }

    /**
     * 初始化
     *
     * @param map           参数
     * @param houseInfoForm 条件参数
     */
    @ModelAttribute
    public void init(Model map, @ModelAttribute HouseInfoForm houseInfoForm, HttpSession session) {
        map.addAttribute("provinceList", redisService.get("provinceList"));
        map.addAttribute("cityList", redisService.get("cityList"));
        map.addAttribute("regionList", redisService.get("regionList"));
        HouseInfoForm newHouseInfoForm = new HouseInfoForm();
        if (houseInfoForm != null) {
            newHouseInfoForm = houseInfoForm;
        }
        SysUser user = (SysUser) session.getAttribute(Constants.SESSION);
        if (user != null && user.getSysRole() != null) {
            newHouseInfoForm.setCompanyId(user.getSysRole().getCompanyId());
        }
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), newHouseInfoForm);
    }

    /**
     * 获取房屋信息列表
     *
     * @param map           参数
     * @param houseInfoForm 条件参数
     * @return 页面
     */
    @RequestMapping(value = "/getAll")
    @SystemControllerLog(description = "获取房屋信息列表")
    public String getAll(Model map, @ModelAttribute HouseInfoForm houseInfoForm) {
        log.info("getAll param HouseInfoForm: {}", houseInfoForm.toString());
        map.addAttribute(String.format(Constants.FORMNAME, ENTITYNAME), houseInfoForm);
        Page<HouseInfo> page = PageHelper.startPage(houseInfoForm.getPageIndex(), houseInfoForm.getPageSize());
        List<HouseInfo> list = houseInfoService.findAll(houseInfoForm);
        map.addAttribute(String.format(Constants.LISTENTITY, ENTITYNAME), list);
        map.addAttribute(Constants.PI, page.toPageInfo());
        return String.format(Constants.LISTPAGE, ENTITYNAME);
    }

    /**
     * 删除房屋信息记录
     *
     * @param id      主键
     * @param request 请求
     * @return 页面
     */
    @RequestMapping(value = "/delete")
    @SystemControllerLog(description = "删除房屋信息记录")
    public String delete(@PathVariable Long id, HttpServletRequest request, SessionStatus status) {
        houseInfoService.delete(id, request);
        elasticsearchHouseInfoService.delete(ENTITYNAME, id);
        status.setComplete();
        return String.format(Constants.REDIRECT, ENTITYNAME);
    }

    /**
     * 删除房屋信息列表
     *
     * @param houseInfoForm 条件参数
     * @param request       请求
     * @return 页面
     */
    @RequestMapping("/deleteAll")
    @SystemControllerLog(description = "删除房屋信息列表")
    public String deleteAll(@ModelAttribute HouseInfoForm houseInfoForm,
                            HttpServletRequest request, SessionStatus status) {
        if (houseInfoForm.getSelectIds() != null) {
            String[] ids = houseInfoForm.getSelectIds().split(Constants.COMMA);
            for (String id : ids) {
                houseInfoService.delete(Long.parseLong(id), request);
                elasticsearchHouseInfoService.delete(ENTITYNAME, id);
            }
        }
        status.setComplete();
        return String.format(Constants.REDIRECT, ENTITYNAME);
    }

    /**
     * 打开房屋信息添加页面
     *
     * @param map 参数
     * @return 页面
     */
    @GetMapping("/add")
    @SystemControllerLog(description = "打开房屋信息添加页面")
    public String openAddPage(Model map) {
        map.addAttribute(ENTITYNAME, new HouseInfo());
        return String.format(Constants.ADDPAGE, ENTITYNAME);
    }

    /**
     * 保存房屋信息添加记录
     *
     * @param houseInfo     实体
     * @param bindingResult 校验
     * @param request       请求
     * @return 页面
     */
    @PostMapping("/add")
    @SystemControllerLog(description = "保存房屋信息添加记录")
    public String postAddMessage(@Valid @ModelAttribute(ENTITYNAME) HouseInfo houseInfo,
                                 BindingResult bindingResult, HttpServletRequest request, SessionStatus status) {
        if (StringUtils.isNotBlank(houseInfo.getHouseName())) {
            List<HouseInfo> list = houseInfoService.findByHouseName(houseInfo.getHouseName());
            if (null != list && !list.isEmpty()) {
                bindingResult.rejectValue("houseName", "misFormat", "这个房屋名称已经存在了！请更改!");
                return String.format(Constants.ADDPAGE, ENTITYNAME);
            }
        }
        if (!bindingResult.hasErrors()) {
            houseInfo.setType(HouseTypeEnum.PRIVATE);
            houseInfoService.save(houseInfo, request);
            elasticsearchHouseInfoService.saveEntity(houseInfo, ENTITYNAME);
            status.setComplete();
            return String.format(Constants.REDIRECT, ENTITYNAME);
        } else {
            return String.format(Constants.ADDPAGE, ENTITYNAME);
        }
    }

    /**
     * 打开房屋信息修改页面
     *
     * @param map 参数
     * @param id  主键
     * @return 页面
     */
    @GetMapping("/edit")
    @SystemControllerLog(description = "打开房屋信息修改页面")
    public String openEditPage(Model map, @RequestParam("id") Long id) {
        map.addAttribute(ENTITYNAME, houseInfoService.findOneWithImage(id));
        return String.format(Constants.EDITPAGE, ENTITYNAME);
    }

    /**
     * 更新房屋信息修改记录
     *
     * @param houseInfo     实体
     * @param bindingResult 校验
     * @param request       请求
     * @return 页面
     */
    @PostMapping("/edit")
    @SystemControllerLog(description = "更新房屋信息修改记录")
    public String postEditMessage(@Valid @ModelAttribute(ENTITYNAME) HouseInfo houseInfo,
                                  BindingResult bindingResult, HttpServletRequest request, SessionStatus status) {
        HouseInfo info = houseInfoService.selectByKey(houseInfo.getId());
        if (!info.getHouseName().equals(houseInfo.getHouseName())) {
            List<HouseInfo> list = houseInfoService.findByHouseName(houseInfo.getHouseName());
            if (null != list && !list.isEmpty()) {
                bindingResult.rejectValue("houseName", "misFormat", "这个房屋名称已经存在了！请更改!");
                return String.format(Constants.EDITPAGE, ENTITYNAME);
            }
        }
        if (!bindingResult.hasErrors()) {
            houseInfoService.updateNotNull(houseInfo, request);
            elasticsearchHouseInfoService.updateEntity(houseInfo, ENTITYNAME);
            status.setComplete();
            return String.format(Constants.REDIRECT, ENTITYNAME);
        } else {
            return String.format(Constants.EDITPAGE, ENTITYNAME);
        }
    }

    /**
     * 浏览房屋信息记录
     *
     * @param map           参数
     * @param id            主键
     * @param houseInfoForm 条件参数
     * @return 页面
     */
    @GetMapping("/view")
    @SystemControllerLog(description = "浏览房屋信息记录")
    public String openViewPage(Model map, @RequestParam("id") Long id,
                               @ModelAttribute HouseInfoForm houseInfoForm) {
        HouseInfo info = houseInfoService.findOneWithImage(id);
        map.addAttribute(ENTITYNAME, info);
        HouseLocation location = houseLocationService.selectByHouseId(id);
        if (location != null) {
            map.addAttribute("lng", location.getLongitude());
            map.addAttribute("lat", location.getLatitude());
        }
        return String.format(Constants.VIEWPAGE, ENTITYNAME);
    }

    /**
     * 打开房屋信息导入页面
     *
     * @return 页面
     */
    @GetMapping("/import")
    @SystemControllerLog(description = "打开房屋信息导入页面")
    public String openImportPage() {
        return "houseInfo/import";
    }

    /**
     * 提交房屋信息导入文件
     *
     * @param map     参数
     * @param file    参数
     * @param request 请求
     * @return 页面
     */
    @PostMapping("/import")
    @SystemControllerLog(description = "提交房屋信息导入文件")
    public String postUploadFile(Model map, @RequestParam MultipartFile file, HttpServletRequest request) {
        if (file != null) {
            try {
                houseInfoService.importData(file.getBytes(), request);
            } catch (Exception e) {
                throw new MyException(ExceptionEnum.CONVERTFILEEXCEPTION, e);
            }
            return String.format(Constants.REDIRECT, ENTITYNAME);
        } else {
            return HttpServletResponseUtil.processModelAndView(map, "最多可以上传6张图片", "houseInfo/import");
        }
    }

    /**
     * 导出房屋信息记录
     *
     * @param houseInfoForm 条件参数
     * @param request       请求
     * @param response      参数
     */
    @GetMapping("/export")
    @SystemControllerLog(description = "导出房屋信息记录")
    public void openExportPage(@ModelAttribute HouseInfoForm houseInfoForm,
                               HttpServletRequest request, HttpServletResponse response) {
        List<Long> list = new ArrayList<>();
        if (houseInfoForm.getSelectIds() != null) {
            String[] ids = houseInfoForm.getSelectIds().split(Constants.COMMA);
            for (String id : ids) {
                list.add(Long.parseLong(id));
            }
        }
        houseInfoService.export(list, request, response);
    }

    /**
     * 获取城市信息列表
     *
     * @param provinceCode 参数
     * @return 页面
     */
    @RequestMapping("/getCityList")
    @ResponseBody
    @SystemControllerLog(description = "获取城市信息列表")
    public String getCityList(String provinceCode) {
        List<ChinaCity> list = (List<ChinaCity>) redisService.get("city" + provinceCode);
        return JSONArray.fromObject(list).toString();
    }

    /**
     * 获取市区信息列表
     *
     * @param cityCode 参数
     * @return 页面
     */
    @RequestMapping("/getRegionList")
    @ResponseBody
    @SystemControllerLog(description = "获取市区信息列表")
    public String getRegionList(String cityCode) {
        List<ChinaRegion> list = (List<ChinaRegion>) redisService.get("region" + cityCode);
        return JSONArray.fromObject(list).toString();
    }

    /**
     * 获取所有房屋信息列表
     *
     * @param response 参数
     */
    @RequestMapping("/getAllHouse")
    @ResponseBody
    @SystemControllerLog(description = "获取所有房屋信息列表")
    public void getAllHouse(HttpServletResponse response) {
//        AjaxJson aj = houseInfoService.getHouseInfoList();
        AjaxJson aj = new AjaxJson();
        Map<String, Object> mapReturn = new HashMap<>();
        mapReturn.putAll(elasticsearchHouseInfoService.getHouseInfoList());
        mapReturn.putAll(houseInfoService.getWholeChinaInfo());
        aj.setSuccess(true);
        aj.setAttributes(mapReturn);
        HttpServletResponseUtil.responseWriter(response, aj);
    }

    /**
     * 打开为房屋设置地理坐标位置
     */
    @RequestMapping("/setLocation")
    @SystemControllerLog(description = "打开为房屋设置地理坐标位置")
    public String setLocation(@RequestParam("id") Long id, Model map) {
        HouseInfo info = houseInfoService.findWithLocation(id);
        HouseLocation location = houseLocationService.selectByHouseId(id);
        if (location != null) {
            map.addAttribute("lng", location.getLongitude());
            map.addAttribute("lat", location.getLatitude());
        }
        map.addAttribute("province", info.getProvinceName());
        map.addAttribute("city", info.getCityName());
        map.addAttribute("region", info.getRegionName());
        map.addAttribute("houseId", id);
        return "houseLocation/add";
    }

    /**
     * 为房屋设置地理坐标位置
     *
     * @param houseId 房屋主键
     * @param lng     经度
     * @param lat     纬度
     */
    @PostMapping("/setLocation")
    @ResponseBody
    @SystemControllerLog(description = "为房屋设置地理坐标位置")
    public String setLocation(Long houseId, String lng, String lat, HttpServletRequest request, HttpServletResponse response) {
        HouseInfo houseInfo = houseInfoService.selectByKey(houseId);
        if (houseId == null) {
            return HttpServletResponseUtil.processErrorStatus(response, "房屋主键不能为空");
        }
        if (lng == null || lat == null) {
            return HttpServletResponseUtil.processErrorStatus(response, "没有选择位置信息");
        }
        HouseLocation location = houseLocationService.selectByHouseId(houseId);
        if (location != null) {
            location.setLongitude(lng);
            location.setLatitude(lat);
            houseLocationService.updateAll(location, request);
        } else {
            location = new HouseLocation();
            location.setHouseId(houseId);
            location.setLongitude(lng);
            location.setLatitude(lat);
            houseLocationService.save(location, request);
        }
        houseInfo.setHouseLocation(location);
        elasticsearchHouseInfoService.updateEntity(houseInfo, "houseInfo");
        return HttpServletResponseUtil.processSuccessStatus(response, "");
    }

}

